package com.ruk.simplehelpers;

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtils {
    public static String camelCaseToSentence(String camelCasedSentence) {
        Pattern pattern = Pattern.compile("[A-Z][^A-Z]*");
        Matcher matcher = pattern.matcher(camelCasedSentence);
        StringBuilder builder = new StringBuilder();
        boolean firstToken = true;

        while (matcher.find()) {
            String word = matcher.group();

            if (firstToken && !camelCasedSentence.startsWith(word)) {
                String firstWord = camelCasedSentence.substring(0, camelCasedSentence.indexOf(word));
                builder.append(firstLetterUpperCase(firstWord));
                firstToken = false;
            }

            if (firstToken) {
                builder.append(word);
            } else {
                builder.append(" ").append(firstLetterLowerCase(word));
            }
            firstToken = false;
        }
        return builder.toString();
    }

    public static String sentenceToCamelCase(String sentence) {
        StringBuilder builder = new StringBuilder();
        StringTokenizer stringTokenizer = new StringTokenizer(sentence);
        while (stringTokenizer.hasMoreTokens()) {
            builder.append(firstLetterUpperCase(stringTokenizer.nextToken()));
        }

        return builder.toString();

    }

    private static String firstLetterUpperCase(String nextToken) {
        StringBuilder builder = new StringBuilder();
        builder.append(nextToken.substring(0, 1).toUpperCase());
        if (nextToken.length() > 1)
            builder.append(nextToken.substring(1, nextToken.length()));
        return builder.toString();
    }

    private static String firstLetterLowerCase(String nextToken) {
        StringBuilder builder = new StringBuilder();
        builder.append(nextToken.substring(0, 1).toLowerCase());
        if (nextToken.length() > 1)
            builder.append(nextToken.substring(1, nextToken.length()));
        return builder.toString();
    }
}
